import { writeFile } from 'node:fs/promises';
import { isPath } from '../../utils';

export const routesTpl = (routes, path) => {
  const routeComponents = routes.map((item: any) => {
    const element = item?.element;
    if (!isPath(element)) {
      return `${item?.id}:${element}`;
    }
    return `${item?.id}:React.lazy(() => import('${element}'))`;
  });

  const tpl = `//@ts-nocheck
      import React from 'react';
      export  function getRoutes() {
      const routes = ${JSON.stringify(routes)} as const;
      return {
        routes,
        routeComponents:{${routeComponents ? `${routeComponents}` : ''}},
      };
      }
    `;
  writeFile(path, tpl);
};

export const runtimeTpl = (path) => {
  const tpl = `
  import { Suspense } from 'react';
  import { RouterProvider as BrowserRouterProvider, createBrowserRouter } from 'react-router-dom';
  import { getRoutes } from './routes';
  // import {Access} from '@/access';
  function buildTree(list: any, itemElement: any) {
    const map = new Map();
    let root: any = [];
  
    list.forEach((item: any) => {
      map.set(item.id, {
        ...item,
        element: itemElement(item),
        children: [],
      });
      if (item.pid === '0') {
        root.push(map.get(item.id));
      } else {
        const parent = map.get(item.pid);
        if (parent) {
          parent.children.push(map.get(item.id));
        }
      }
    });
  
    return root;
  }

   const { routes, routeComponents } = getRoutes();

    const itemElement = (item: any) => {
      let View = (routeComponents as any)?.[item?.id];
      const route = (
        <Suspense>
          <View />
        </Suspense>
      );
  
      // if (item?.access) {
      //   return (
      //     <Access code={item?.access} path={item?.path}>
      //       {route}
      //     </Access>
      //   );
      // }
      return route;
    };
  
    const tree = buildTree(routes, itemElement);
    const router = createBrowserRouter(tree);
    export const RouterProvider = (props: any) => {
    const { loading, noFoundLayout, ...rest } = props || {};
  
    return <BrowserRouterProvider router={router} fallbackElement={noFoundLayout} {...rest} />;
  };
 `;
  writeFile(path, tpl);
};
